﻿using System;
using System.Collections;
using System.Data;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.Services;
using System.Web.Services.Protocols;
using System.Xml.Linq;
using DBLOG.KmlWrapper;
using System.Web.Configuration;
using LetsDoItWS.BO;

namespace LetsDoItWS
{
    /// <summary>
    /// WastesKml - kml file generator
    /// </summary>
    public class WastesKml : IHttpHandler
    {

        public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "application/vnd.google-earth.kml+xml";// "text/plain";

            KmlDocument document = new KmlDocument();

            decimal lngLeft = 0, lngRight = 0, latTop = 0, latBottom = 0;
            if(!string.IsNullOrEmpty(context.Request.QueryString["BBOX"]))
            {
                string[] splitCoord = context.Request.QueryString["BBOX"].ToString().Split(',');
                lngLeft = Convert.ToDecimal(splitCoord[0]);
                latBottom = Convert.ToDecimal(splitCoord[1]);
                lngRight = Convert.ToDecimal(splitCoord[2]);
                latTop = Convert.ToDecimal(splitCoord[3]);
            }
            
            decimal maximumSecondsToTPT = string.IsNullOrEmpty(WebConfigurationManager.AppSettings["MaximumSecondsToTPT"]) ?
                (decimal)1 :
                Convert.ToDecimal(WebConfigurationManager.AppSettings["MaximumSecondsToTPT"]);
            if (Math.Abs(lngLeft - lngRight) < maximumSecondsToTPT)
            {
                using (ldirdbEntities dataContext = new ldirdbEntities())
                {
                    KmlStyle style = new KmlStyle();
                    style.IconImageUrl = System.Configuration.ConfigurationManager.AppSettings["IconImageUrl"];
                    style.Id = "trash_icon";

                    foreach (TrashPoint point in dataContext.TrashPoints.Where(tp =>
                                                                               (string.IsNullOrEmpty(tp.test_tpt.Trim()) || tp.test_tpt.ToLower()=="n") &&
                                                                               (string.IsNullOrEmpty(tp.exclude_TPT.Trim()) || tp.exclude_TPT.ToLower()=="n") &&
                                                                               tp.longitude_TPT != null &&
                                                                               tp.latitude_TPT != null &&
                                                                               tp.longitude_TPT > lngLeft &&
                                                                               tp.longitude_TPT < lngRight &&
                                                                               tp.latitude_TPT > latBottom &&
                                                                               tp.latitude_TPT < latTop).ToList())
                    {
                        KmlPlacemark kp1 = new KmlPlacemark();
                        kp1.Name = point.id_TPT.ToString(); //
                        string descTemplate = @"<p>([ID]) [DESCRIPTION]</p>" +
                                              "<p>Uploaded at [DATETIME]</p>" +
                                              "<p>By [USERNAME]</p>"; // +
                        if (!string.IsNullOrEmpty(point.photo1_TPT))
                        {
                            descTemplate += "<img src=\"" + ImageStorageFactory.GetFirstImageURL(point.id_TPT) +
                                            "\" />";
                        }
                        if (!string.IsNullOrEmpty(point.photo2_TPT))
                        {
                            descTemplate += "<img src=\"" + ImageStorageFactory.GetSecondImageURL(point.id_TPT) +
                                            "\" />";
                        }
                        string desc = descTemplate.Replace("[DESCRIPTION]", point.description_TPT);
                        desc = desc.Replace("[DATETIME]", ((DateTime) point.date_time_TPT).ToString("dd/MM/yyyy"));
                        User userInfo = dataContext.Users.FirstOrDefault(u => u.id == point.user_TPT);
                        string userName = userInfo != null ? userInfo.name : string.Empty;
                        desc = desc.Replace("[USERNAME]", userName);
                        desc = desc.Replace("[ID]", point.id_TPT.ToString());
                        kp1.Description = desc;
                        kp1.KmlStyle = style;
                        KmlPoint kpoint = new KmlPoint();
                        kpoint.Latitude = point.latitude_TPT.ToString();
                        kpoint.Longitude = point.longitude_TPT.ToString();
                        kp1.KmlPoint = kpoint;

                        document.Add(kp1);
                    }
                }
            }
            else
            {
                //county summary report
                using (ldirdbEntities dataContext = new ldirdbEntities())
                {
                    KmlStyle style = new KmlStyle();
                    style.IconImageUrl = "http://ldir-mobile.gtstelecom.ro/LetsDoItWS/images/ldir_point.png";
                        // "http://localhost:2970/images/ldir_point.png";
                    style.Id = "trash_icon";

                    foreach (PointsByCounty county in dataContext.PointsByCounties)
                    {
                        KmlPlacemark kpCounty = new KmlPlacemark();
                        kpCounty.Name = string.Format("{0} ({1})", county.County, county.NrPoints);
                        kpCounty.Description = kpCounty.Name;
                        kpCounty.KmlStyle = style;
                        KmlPoint kpoint = new KmlPoint();
                        kpoint.Latitude = county.Y.ToString();
                        kpoint.Longitude = county.X.ToString();
                        kpCounty.KmlPoint = kpoint;

                        document.Add(kpCounty);
                    }
                }
            }


            KmlGenerator generator = new KmlGenerator(document);
            generator.KmlDescription = "LDIR wastes desc";
            generator.KmlName = "LDIR wastes";
            generator.GenerateKml();

            context.Response.Write(generator.ToString());
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}
